package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.properties.WechatMiniProgramProperties;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class WechatServiceImpl implements WechatService {
    // 登陆小程序：获取code/detailCode  用code去登陆微信获取openId  登陆后获取Token 带着token和detailcode 拿到手机号码


    @Autowired
    private WechatMiniProgramProperties wechatMiniProgramProperties;
// 找微信要openId
 private static final String OPENID_URL
        ="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
// 找微信要Token
 private static final String ACCESS_TOKEN_URL
        ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

 private static final String PHONE_URL
         ="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


// 获取微信登陆权限后，后端要和微信交互的代码

    // 1 小程序登陆，为了得到 openId
    @Override   // 请求get1 ：小程序的申请的id/密码  请求路径url
    public String getOpenid(String code) {
        // 请求参数
        Map<String,Object> paramMap= new HashMap<>();
        paramMap.put("appid",wechatMiniProgramProperties.getAppId());
        paramMap.put("secret",wechatMiniProgramProperties.getAppSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        // 发送请求，接受结果
        String result = HttpUtil.get(OPENID_URL,paramMap);
        //解析结果
        JSONObject jsonObject = JSONUtil.parseObj(result);
        Integer errcode = jsonObject.getInt("errcode");

        if(ObjectUtil.isNotEmpty(errcode)){
            log.error("获取code失败，错误码：{} 错误信息：{}",errcode,jsonObject.getStr("errmsg"));
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }

    // 2 ，检验登录态，为了得到access_token
    private String getAccessToken(){
        // 请求参数
        Map<String,Object> paramMap= new HashMap<>();
        paramMap.put("appid",wechatMiniProgramProperties.getAppId());
        paramMap.put("secret",wechatMiniProgramProperties.getAppSecret());
        paramMap.put("grant_type","authorization_code");
        // 发送请求，接受结果
        String result = HttpUtil.get(ACCESS_TOKEN_URL,paramMap);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("erromsg"));
        }
        return jsonObject.getStr("access_token");
    }


    //3  为了得到手机号码phone 带着accessToken，发出post获取手机号，detailCode在登陆小程序时和code一起获取
    @Override
    public String getPhone(String detailCode) {
        // 获取access-token 凭据
        String accessToken = getAccessToken();
        String url = PHONE_URL+accessToken;
        Map<String ,String>  codeMap = new HashMap<>();
        codeMap.put("code",detailCode);

      String result = HttpUtil.post(url,
                        JSONUtil.toJsonStr(codeMap) );
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(jsonObject.getInt("errcode")!=0){
            log.error("获取手机号phone失败，错误码：{} 错误信息：{}",
                    jsonObject.getInt("errcode"),
                    jsonObject.getStr("errmsg"));
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }





 /*
  // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${zzyl.wechat.appId}")
    private String appid;

    @Value("${zzyl.wechat.appSecret}")
    private String secret;


  // 获取openid
    @Override
    public String getOpenid(String code) {

        //获取公共参数
        Map<String,Object> paramMap = getAppConfig();
        paramMap.put("js_code",code);

        String result = HttpUtil.get(REQUEST_URL, paramMap);
        //是一个map
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口响应是否出错
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        String openid = jsonObject.getStr("openid");

        return openid;
    }

    //封装公共参数
    private Map<String, Object> getAppConfig() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        return paramMap;
    }

  //获取手机号
    @Override
    public String getPhone(String detailCode) {

        String token = getToken();
        String url = PHONE_REQUEST_URL+token;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code",detailCode);
        //发起请求
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        //是一个map
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口响应是否出错
        if(jsonObject.getInt("errcode") != 0){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

   //获取token
    private String getToken() {

        Map<String, Object> paramMap = getAppConfig();
        //发起请求
        String result = HttpUtil.get(TOKEN_URL, paramMap);
        //是一个map
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口响应是否出错
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        String token = jsonObject.getStr("access_token");

        return token;

    }*/
}
